﻿Imports Odyssee.WebControles

Public Class FicheContact
    Inherits FichePage(Of Integer, ServiceContacts.Contact, ServiceContacts.ContactsClient, ServiceContacts.CriteresRechercheContact)

    Public Overrides ReadOnly Property Titre As String
        Get
            Return "Fiche contact"
        End Get
    End Property
    Protected Overrides ReadOnly Property LibelleEntite As String
        Get
            Return "contact"
        End Get
    End Property
    Protected Overrides ReadOnly Property LibelleFeminin As Boolean
        Get
            Return False
        End Get
    End Property
    Protected Overrides ReadOnly Property LibelleApostrophe As Boolean
        Get
            Return False
        End Get
    End Property
    Protected Overrides ReadOnly Property PopupPanel As JQPopupPanel
        Get
            Return Me.pnlContact
        End Get
    End Property
    Protected Overrides ReadOnly Property BoutonActualiser As Button
        Get
            Return Me.btnActualiser
        End Get
    End Property
    Protected Overrides ReadOnly Property SeparateurActualiser As ToolBarSeparator
        Get
            Return Me.tbSep1
        End Get
    End Property
    Protected Overrides ReadOnly Property BoutonEnregistrer As Button
        Get
            Return Me.btnEnregister
        End Get
    End Property


    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.CtrlAdresse.Initialiser()

        If IsPostBack Then
            If Request.Form("__EVENTTARGET") = "btnAjouterEntreprise" Then
                Me.pnlContact.ShowPopup("~/Tiers/LienEntrepriseContact.aspx", "&cleContact=" & Me.CleEntite.ToString & "&cleEntreprise=" & Server.UrlEncode(Request.Form("ctl00$content$pnlContact__hidden1")), ,,,,,,,,,,, True, , , , "Lien entreprise / contact", "600", "720")
            ElseIf Request.Form("__EVENTTARGET") = "content_pnlContact__button" Then
                InitialiserLiensEntreprises()
            End If
        ElseIf Me.ModeFiche = Tools.ModeFiche.Creation Then
            SetFocus(Me.cmbQualite)
        ElseIf Me.ModeFiche = Tools.ModeFiche.Modification Then
            SetFocus(Me.txtNom)
        End If
    End Sub

    Private Sub gvEntreprises_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles gvEntreprises.RowCommand
        Dim cleEntreprise As String = ""
        Dim fonction As String = ""

        If e.CommandArgument Is Nothing Then Return
        cleEntreprise = CStr(e.CommandArgument)
        If cleEntreprise.Contains("¤") Then
            fonction = cleEntreprise.Split("¤"c)(1)
            cleEntreprise = cleEntreprise.Split("¤"c)(0)
        End If

        Select Case e.CommandName.ToUpper
            Case "MODIFIER"
                Response.Redirect("~/Tiers/FicheEntreprise.aspx?modeFiche=1&cle=" & cleEntreprise)

            Case "SUPPRIMER"
                SupprimerLienEntreprise(cleEntreprise, fonction)

        End Select
    End Sub


    Protected Overrides Function InitialiserCriteresRechercheEntite(cle As Integer) As ServiceContacts.CriteresRechercheContact
        Dim criteres As New ServiceContacts.CriteresRechercheContact
        criteres.Authentication = New ServiceContacts.AuthenticationParameters
        criteres.Authentication.Token = Tools.GetInstance.getToken
        criteres.Cle = cle
        Return criteres
    End Function
    Protected Overrides Function RechercherEntite(svc As ServiceContacts.ContactsClient, criteres As ServiceContacts.CriteresRechercheContact, ByRef ok As Boolean, ByRef messageErreur As String) As List(Of ServiceContacts.Contact)
        Dim results As ServiceContacts.ResultatRechercheContact
        results = svc.Recherche(criteres)
        If results Is Nothing Then Return Nothing
        ok = results.OK
        messageErreur = results.ErrorMessage
        Return results.Contacts
    End Function
    Protected Overrides Sub InitialiserObjetEntite(entite As ServiceContacts.Contact)
        If entite.Adresse Is Nothing Then entite.Adresse = New ServiceContacts.Adresse
        If entite.ZoneSup Is Nothing Then entite.ZoneSup = New ServiceContacts.ZoneSup
    End Sub

    Protected Overrides Sub InitialiserParametres()
        MyBase.InitialiserParametres()

        ' Chargement de la liste des qualités
        Me.cmbQualite.Items.Clear()
        Using svc As New ServiceParametre.ParametresClient
            Dim params As New ServiceParametre.OperationParameters
            params.Authentication = New ServiceParametre.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken

            Try
                Dim results As ServiceParametre.OIItemListResult = svc.ListeQualites(params)
                If results Is Nothing OrElse Not results.OK Then
                    Tools.NotifyErreur(Me, "Impossible de charger la liste des qualités" & If(results Is Nothing, ".", " : " & ControlChars.NewLine & results.ErrorMessage))
                Else
                    For Each item As ServiceParametre.OIItem In results.Liste
                        Me.cmbQualite.Items.Add(New ListItem(item.Libelle, item.Code))
                    Next
                    Me.cmbQualite.SelectedIndex = 0
                End If
            Catch ex As Exception
                Tools.NotifyErreur(Me, ex.Message)
            End Try
        End Using

        ' Chargement de la liste des types
        Dim result As String = Tools.LoadParametersCombo(Me.cmbType, "types de contact", 13)
        If result <> "" Then
            NotifyErreur(result)
            Return
        End If

    End Sub


    Protected Overrides Sub InitialiserPage()
        MyBase.InitialiserPage()

        Select Case Me.ModeFiche

            Case Tools.ModeFiche.Creation
                Me.divEntreprises.Visible = False

            Case Tools.ModeFiche.Modification
                ' Contact
                Me.cmbQualite.SelectedValue = Me.Entite.Qualite
                Me.txtNom.Text = Me.Entite.Nom
                Me.txtPrenom.Text = Me.Entite.Prenom
                Me.cmbType.Text = Me.Entite.Type
                Me.CtrlAdresse.AffecterValeurs(Me.Entite.Adresse)
                Me.txtTelephone.Text = Tools.FormaterNumeroTelephone(Me.Entite.Telephone)
                Me.txtPortable.Text = Tools.FormaterNumeroTelephone(Me.Entite.Portable)
                Me.txtEMail.Text = Me.Entite.Email
                Me.txtCode.Text = Me.Entite.Cle.ToString

                ' Entreprises
                InitialiserLiensEntreprises()

        End Select
    End Sub

    Private Sub InitialiserLiensEntreprises()
        Using svc As New ServiceContacts.ContactsClient
            Dim params As New ServiceContacts.ParametresLectureLienContactEntreprise
            params.Authentication = New ServiceContacts.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.CleContact = Me.CleEntite

            Dim results As ServiceContacts.ResultatListeLiensContactEntreprise = Nothing
            Try
                results = svc.LectureLiensContactEntreprise(params)
                If results Is Nothing OrElse Not results.OK Then
                    NotifyErreur("Impossible de charger les entreprises du contact '" & Me.CleEntite & "'" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                Else
                    Me.gvEntreprises.DataSource = results.Liens
                    Me.gvEntreprises.DataBind()
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using
    End Sub
    Protected Sub SupprimerLienEntreprise(cleEntreprise As String, fonction As String)
        Using svc As New ServiceContacts.ContactsClient
            Dim params As New ServiceContacts.ParametresLectureLienContactEntreprise
            params.Authentication = New ServiceContacts.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.CleContact = Me.CleEntite
            params.CleEntreprise = cleEntreprise
            params.Fonction = fonction

            Try
                Dim results As ServiceContacts.OperationResult
                results = svc.SupprimerLienContactEntreprise(params)
                If results.OK Then
                    NotifySuccess("Suppression effectuée avec succès.")
                    InitialiserLiensEntreprises()
                Else
                    NotifyErreur(results.ErrorMessage)
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using
    End Sub


    Protected Overrides Function Renseigner() As Boolean
        Me.Entite.Qualite = Me.cmbQualite.SelectedValue
        Me.Entite.Nom = Me.txtNom.Text
        Me.Entite.Prenom = Me.txtPrenom.Text
        Me.Entite.Type = Me.cmbType.Text
        Me.Entite.Adresse.Pays = "FR"
        Me.CtrlAdresse.RecupererValeurs(Me.Entite.Adresse)
        Me.Entite.Telephone = Me.txtTelephone.Text
        Me.Entite.Portable = Me.txtPortable.Text
        Me.Entite.Email = Me.txtEMail.Text
        Return True
    End Function
    Protected Overrides Function Creer() As Boolean
        Dim cleContact As Integer = 0

        ' Vérification de la commune
        If Not Me.CtrlAdresse.ValiderCommune() Then Return False

        ' Création du contact
        Using svc As New ServiceContacts.ContactsClient
            Dim params As New ServiceContacts.ParametresCreationContact
            params.Authentication = New ServiceContacts.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.Contact = Me.Entite

            Try
                Dim results As ServiceContacts.ResultatCreationContact = svc.Creation(params)
                If results Is Nothing OrElse Not results.OK Then
                    NotifyErreur("Impossible de créer le contact" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                    Return False
                Else
                    cleContact = results.CleContact
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
                Return False
            End Try
        End Using

        Me.Entite.Cle = cleContact
        Me.CleEntite = cleContact

        Return True
    End Function
    Protected Overrides Function MettreAJour() As Boolean
        ' Vérification de la commune
        If Not Me.CtrlAdresse.ValiderCommune() Then Return False

        ' Mise à jour du contact
        Using svc As New ServiceContacts.ContactsClient
            Dim params As New ServiceContacts.ParametresCreationContact
            params.Authentication = New ServiceContacts.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.Contact = Me.Entite

            Try
                Dim results As ServiceContacts.OperationResult = svc.MiseAJour(params)
                If results Is Nothing OrElse Not results.OK Then
                    NotifyErreur("Impossible de mettre à jour le contact" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                    Return False
                Else
                    NotifySuccess("Contact mis à jour avec succès.")
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
                Return False
            End Try
        End Using

        Return True
    End Function


End Class